<template>
  <div class="baseinfo">
    <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-model-item label="项目编号" prop="projectNo" :label-col="{ span: 8 }" :wrapper-col="{ span: 15 }">
            {{form.projectNo}}
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item
            ref="projectRealName"
            label="项目名称*"
            prop="projectRealName" 
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-input
              v-model="form.projectRealName"
              @blur="
                () => {
                  $refs.projectRealName.onFieldBlur()
                }
              "
              placeholder="真实名称，打印不显示"   
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item
            ref="projectName"
            label="项目名称"
            prop="projectName" 
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-input
              v-model="form.projectName"
              @blur="
                () => {
                  $refs.projectName.onFieldBlur()
                }
              "
              placeholder="脱密名称,针对产品类项目，名称规则：年份（****年）+**（品类）产品+字母（按当年研发顺序用ABCDEF等大写字母代替）；如2021年酱油产品A"    
              title="脱密名称,针对产品类项目，名称规则：年份（****年）+**（品类）产品+字母（按当年研发顺序用ABCDEF等大写字母代替）；如2021年酱油产品A"    
            />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-model-item
            ref="mainDeptName"
            label="主导经营体"
            prop="mainDeptName"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-input
              v-model="form.mainDeptName" 
              @blur="
                () => {
                  $refs.mainDeptName.onFieldBlur()
                }
              "
              placeholder="请填写正确的组织架构名称，系统自动校验"
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item
            label="项目分类"
            prop="projectTypeSubCategory" 
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <!-- <a-select
              v-model="form.projectTypeSubCategory"
              placeholder="请选择项目分类"
              :options="projectCategoryOptions"  :disabled="form.id!=''"  
            >
              <a-icon slot="suffixIcon" type="plus" />
            </a-select> -->
            <span style="color: #f7a961; margin: 0 6px; font-size: 16px">{{ subName }}</span>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item
            ref="implementPlace"
            label="横向品牌名称"
            prop="implementPlace"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-input
              v-model="form.implementPlace"  
              @blur="
                () => {
                  $refs.implementPlace.onFieldBlur()
                }
              "
              placeholder="本项目的产品属于横向品牌的请填写横向品牌名称，没有的可以不填" title="本项目的产品属于横向品牌的请填写横向品牌名称，没有的可以不填"
            />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="24">
          <a-form-model-item
            ref="projectContent"
            label="项目内容概述"
            prop="projectContent"
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 20 }"
          >
            <a-textarea
              v-model="form.projectContent"
              @blur="
                () => {
                  $refs.projectContent.onFieldBlur()
                }
              "
              :auto-size="{ minRows: 3, maxRows: 5 }"
              style="width: 100%"
            />
          </a-form-model-item>
        </a-col>
      </a-row>

      <five-to-five ref="fiveForm" :projectBuildId="projectBuildId" :change-id="changeId" @addField="addFiveDataToForm"/>
    </a-form-model>

    <pagination-select
      :title="hatch.title"
      :searchPlaceholder="hatch.searchPlaceholder"
      :visible="hatch.visible"
      :url="hatch.url"
      :columns="hatch.columns"
      @hatchHandleOk="hatchHandleOk"
    />
  </div>
</template>
<script>
import $ from 'jquery'
import { getAction, getActionAsync, postAction, postActionAsync } from '@/api/manage'
import { getParamValFromUrl, strNotNull } from '@/utils/common.js'
import Vue from 'vue'
export default {
  components: {
    PaginationSelect: () => import('@/components/tools/PaginationSelect'),
    FiveToFive: () => import('@/components/tools/projectBuildStup/baseInfo/FiveToFive')
  },
  props: {
    projectBuildId: {
      Type: String,
      default: '',
    },
    changeId: {
      Type: String,
      default: ''
    },
    selProjectType: {
      Type: String,
      default: '',
    }
  },
  data() {
    return {
      labelCol: { span: 8 },
      wrapperCol: { span: 15 },
      other: '',
      subName: '',
      form: {
        id: '',
        projectClass: '10',
        projectNo: '',
        projectName: '',
        mainDeptName: '',
        projectTypeSubCategory: '',
        projectType: '',
        hatchProjectId: '',
        hatchProjectNo: '',
        hatchProjectName: '',
        lastProjectNo: '',
        lastProjectName: '',
        keywords: '',
        highTechType: '',
        isHighTechProject: false,
        isHighTechProjectText: '',
        projectContent: '',
        projectUseFor: '',
        isNeedEngineeringMotion: null,
        motionProjectNameOrNo: '',
        functionAndPerformance: '',
        sourceBefore: '',
        technologyTarget: '',
        economyTarget: '',
        implementPlace:'',
        name: '',
        delivery: false,
        type: [],
        resource: '',
        desc: '',
        status: 0 
      },
      rules: {
        projectName: [
          { required: true, message: '脱密名称,针对产品类项目，名称规则：年份（****年）+**（品类）产品+字母（按当年研发顺序用ABCDEF等大写字母代替）；如2021年酱油产品A', trigger: 'blur' },
          { min: 1, max: 50, message: '项目名不超过50个字符', trigger: 'blur' },
        ],
        projectRealName: [
          { required: false, message: '真实名称，打印不显示', trigger: 'blur' },
          { min: 1, max: 50, message: '项目名不超过50个字符', trigger: 'blur' },
        ],
        keywords: [
          {
            required: true,
            message: '请输入与项目相关的关键词，多个关键词用中文分号[;]隔开，至少填写5个关键词，如：菌种，发酵等',
            trigger: 'blur',
          },
          { min: 1, max: 127, message: '关键词不超过127个字符', trigger: 'blur' },
        ],
        projectContent: [
          { required: true, message: '请输入项目概述', trigger: 'blur' },
          { min: 1, max: 2000, message: '项目概述不超过2000个字符', trigger: 'blur' },
        ],
        projectUseFor: [
          { required: true, message: '请输入项目应用场景', trigger: 'blur' },
          { min: 1, max: 2000, message: '项目应用场景不超过2000个字符', trigger: 'blur' },
        ],
        // functionAndPerformance: [
        //   { required: true, message: '请输入功能和性能要求', trigger: 'blur' },
        //   { min: 1, max: 300, message: '功能和性能要求不超过300个字符', trigger: 'blur' },
        // ],
        technologyTarget: [
          { required: true, message: '请输入项目技术目标', trigger: 'blur' },
          { min: 1, max: 300, message: '项目技术目标不超过300个字符', trigger: 'blur' },
        ],
        economyTarget: [
          { required: true, message: '请输入项目经济目标', trigger: 'blur' },
          { min: 1, max: 300, message: '项目经济目标不超过300个字符', trigger: 'blur' },
        ],
        mainDeptName: [
          { required: true, message: '请输入主导经营体', trigger: 'blur' },
          { min: 1, max: 300, message: '主导经营体不超过300个字符', trigger: 'blur' },
        ],
        projectTypeSubCategory: [{ required: true, message: '请选择项目分类', trigger: 'change' }],
        highTechType: [{ required: true, message: '请选择项目所属高企大类', trigger: 'change' }],
        designSource: [
          {
            type: 'array',
            required: true,
            message: '请选择设计开发来源',
            trigger: 'change',
          },
        ],
        isNeedEngineeringMotion: [{ required: true, message: '请选择是否需要工程动议', trigger: 'change' }],
        desc: [{ required: true, message: '请选择是否需要工程动议', trigger: 'blur' }],
      },

      projectCategoryOptions: [],
      highCategoryOptions: [],
      designSourceOptions: [],
      url: {
        codeInfoList: '/manage/codeInfo/list',
        getProjectByNo: '/projectBuild/getProjectByNo',
        save: '/projectBuild/add',
        queryVOById: '/projectBuild/queryVOById',
      },
      hatch: {
        visible: false,
        title: '请选择孵化项目',
        searchPlaceholder: '输入代码或名称查询',
        url: '/hatchProject/listBySelect',
        columns: [
          {
            title: '孵化项目编号',
            dataIndex: 'hatchProjectNo',
            align: 'center',
          },
          {
            title: '孵化项目名称',
            dataIndex: 'hatchProjectName',
            align: 'center',
          },
        ],
      },
      loadFinish: false
    }
  },
  computed: {},
  methods: {
    addFiveDataToForm(val,valRef) {
      this.$set(this.form, valRef, val)
    },
    async doSubmit() {
      if(!this.loadFinish){
        layer.message.warning('请等待页面加载完毕')
        return {}  
      }
      var validR=false;
      try{
        validR = await this.$refs.ruleForm.validate();
        validR = await this.$refs.fiveForm.checkFiveWriteStatus()
      }catch(e){
        validR = false;
      }
      console.log('validR',validR);
      this.form.validResult = validR;
      let res=await this.doSave()
        this.projectBuildId=res;
      return {valid:validR,id:res};
    },
    async doSave() {
      let flag=null;
      var keywords = this.form.keywords
      if (strNotNull(keywords)) {
        let keywordLen = keywords.split('；').filter((x) => !!x).length
        if (keywordLen < 5 || keywordLen > 8) {
          this.$message.warning('请填写5-8个关键词, 中文分号[；]分隔');
          return flag;
        }
      }
      var formData = JSON.parse(JSON.stringify(this.form));
      if (formData.designSource!=null && formData.designSource.length>0) {
        formData.designSource = formData.designSource.join(',')
      }else{
        formData.designSource = '';
      }
      formData.changeId=this.changeId;
      var vm = this
      await postActionAsync(this.url.save, formData)
        .then((res) => {
          if (res.code == 200) {
            vm.form.id = res.result.id;
            vm.form.projectNo = res.result.projectNo;
            this.$message.success('保存成功')
            return flag=res.result.id;
          } else {
            this.$message.warning('保存数据出错:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('保存数据出错:' + res.message)
        })
        return flag;
    },
    resetForm() {
      this.$refs.ruleForm.resetFields()
    },
    //初始化项目子类
    initProjectCategoryOptions() {
      var vm = this
      getAction(this.url.codeInfoList, { type: '项目子类', isdel: 0, parentid: vm.form.projectClass,pageSize:-1 })
        .then((res) => {
          if (res.code == 200) {
            var list = res.result
            if (list != null) {
              list.records.map((item) => {
                vm.projectCategoryOptions.push({ value: item.code, label: item.name })
              })
            }
          } else {
            this.$message.warning('查询项目子类失败:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('查询项目子类失败:' + res.message)
        })
    },
    initSubName () {
      var vm = this
      getAction(this.url.codeInfoList, { type: '项目子类', isdel: 0,parentid:vm.form.projectClass,code:vm.form.projectType,pageSize:-1})
        .then((res) => {
          if (res.code == 200) {
            var list = res.result
            if (list != null) {
              this.subName = list.records[0].name
            }
          } else {
            this.$message.warning('项目子类:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('项目子类:' + res.message)
        })
    },
    //初始化项目所属高企大类
    initHighCategoryOptions() {
      var vm = this
      getAction(this.url.codeInfoList, { type: '项目所属高企大类',pageSize:-1 })
        .then((res) => {
          if (res.code == 200) {
            var list = res.result
            if (list != null) {
              list.records.map((item) => {
                vm.highCategoryOptions.push({ value: item.code, label: item.name })
              })
            }
          } else {
            this.$message.warning('查询项目所属高企大类失败:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('查询项目所属高企大类失败:' + res.message)
        })
    },
    //立项设计来源选项
    initSourceDesign() {
      var vm = this
      getAction(vm.url.codeInfoList, { type: '项目立项设计来源',pageSize:-1 }).then((res) => {
        if (res.code == 200) {
          res.result.records.forEach((element) => {
            vm.designSourceOptions.push({
              label: element.name,
              value: element.code,
            })
          })
        } else {
          this.$message.warning('加载【项目立项设计来源】选项有误：' + res.message)
        }
      })
    },
    //孵化项目选中
    hatchHandleOk(record) {
      if (record != null && record.length > 0) {
        this.form.hatchProjectId = record[0].id
        this.form.hatchProjectNo = record[0].hatchProjectNo
        this.form.hatchProjectName = record[0].hatchProjectName
      }
      this.hatch.visible = false
    },
    //校验关联项目号
    checkPreProject() {
      if (this.form.lastProjectNo != null && this.form.lastProjectNo.length > 0) {
        var vm = this
        getAction(this.url.getProjectByNo, { projectNo: this.form.lastProjectNo })
          .then((res) => {
            if (res.code == 200) {
              var result = res.result
              if (result != null) {
                this.form.lastProjectName = result.projectName
              } else {
                this.form.lastProjectNo = ''
                vm.$message.warning('请输入有效的【关联项目号】')
              }
            } else {
              this.$message.warning('查询关联项目失败:' + res.message)
            }
          })
          .catch((res) => {
            this.$message.warning('查询关联项目失败:' + res.message)
          })
      }
    },
    //高企大类变化，设置高企标识
    highCategoryChange() {
      var highCategory = this.form.highTechType
      this.form.isHighTechProjectText =
        highCategory == null || highCategory == '' ? '' : highCategory === '99' ? '非高企项目' : '高企项目'
      if (this.form.isHighTechProjectText == '高企项目') {
        this.form.isHighTechProject = true
      }else{
        this.form.isHighTechProject = false
      }
    },
    //如果有id，则加载已填写信息
    initData() {
      if (this.projectBuildId != null && this.projectBuildId != '') {
        var vm = this
        getAction(this.url.queryVOById, { id: this.projectBuildId,changeId:this.changeId})
          .then((res) => {
            if (res.code == 200) {
              var result = res.result
              if (result != null) {
                this.form = result
                if (this.form.isHighTechProject) {
                  this.form.isHighTechProjectText = '高企项目'
                } else {
                  this.form.isHighTechProjectText = '非高企项目'
                }
                //设计开发来源
                var ds = vm.form.designSource
                if (ds == undefined || ds == null || ds == '') {
                  vm.form.designSource = []
                } else {
                  vm.form.designSource = ds.split(',')
                }
                this.initSubName()
                this.loadFinish=true
              } else {
                vm.$message.warning('初始化项目信息为空')
              }
            } else {
              this.$message.warning('初始化项目信息失败:' + res.message)
            }
          })
          .catch((res) => {
            this.$message.warning('初始化项目信息失败:' + res.message)
          })
      }else{
        this.loadFinish=true
      }
    },
  },
  mounted() {
     if (this.projectBuildId == null || this.projectBuildId == '') {
        this.form.projectType = this.selProjectType
        this.form.projectTypeSubCategory = this.selProjectType
        this.initSubName()
     }

    this.initProjectCategoryOptions()
    this.initHighCategoryOptions()
    this.initSourceDesign()
    this.initData()
  },
}
</script>
<style lang="less" scoped>
/deep/ .ant-btn-primary {
  width: 85px;
  height: 30px;
  border-radius: 2px;
  background: #4095e4;
  margin-right: 10px;
}
/deep/ .default {
  width: 85px;
  height: 30px;
  border-radius: 2px;
}
.baseinfo {
  background-color: #fff;
  border: 1px solid #eaeaea;
  padding: 30px;
  .btn {
    display: flex;
    justify-content: center;
  }
}
</style>